package com.rui.realm;

import com.rui.domain.User;
import com.rui.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public void setName(String name) {
        //super.setName("CustomerRealm");
        super.setName(name);
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //获取用户输入的用户名
        String username = (String) token.getPrincipal();
        System.out.println("AuthenticationInfo>username="+username);
        // 使用用户名从数据库中查出 凭证
        User user = userService.findUserByUsername(username);

        SimpleAuthenticationInfo authenticationInfo =
                new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());

        return authenticationInfo;
    }


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        //获取用户信息
        User user = (User) principal.getPrimaryPrincipal();

        Set<String> roles = new HashSet<>();
        //根据roleId查询角色
        if (user.getRoleId()==1) {
            roles.add("academic");
        }else if (user.getRoleId()==2) {
            roles.add("teacher");
        }else if (user.getRoleId()==3) {
            roles.add("student");
        }


        //创建授权对象SimpleAuthorizationInfo
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.setRoles(roles);

        return authorizationInfo;
    }
}
